package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.OrderConfigMapper;
import com.qingcheng.dao.OrderItemMapper;
import com.qingcheng.dao.OrderLogMapper;
import com.qingcheng.dao.OrderMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.order.*;
import com.qingcheng.service.goods.SkuService;
import com.qingcheng.service.order.CartService;
import com.qingcheng.service.order.OrderService;
import com.qingcheng.util.IdWorker;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Service(interfaceClass = OrderService.class )
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private OrderConfigMapper orderConfigMapper;


    /**
     * 返回全部记录
     * @return
     */
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }

    /**
     * 分页查询
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Order> findPage(int page, int size) {
        PageHelper.startPage(page,size);
        Page<Order> orders = (Page<Order>) orderMapper.selectAll();
        return new PageResult<Order>(orders.getTotal(),orders.getResult());
    }

    /**
     * 条件查询
     * @param searchMap 查询条件
     * @return
     */
    public List<Order> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return orderMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Order> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(example);
        return new PageResult<Order>(orders.getTotal(),orders.getResult());
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    public Order findById(String id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增
     * @param order
     */
    public void add(Order order) {
        orderMapper.insert(order);
    }

    /**
     * 修改
     * @param order
     */
    public void update(Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     *  删除
     * @param id
     */
    public void delete(String id) {
        orderMapper.deleteByPrimaryKey(id);
    }


    /**
     * 根据id去查询订单以及订单的详情
     * @param id
     * @return
     */
    public OrderOrderItem findOrderOrderItemByid(String id) {
        //根据id去查询订单信息
        Order order = orderMapper.selectByPrimaryKey(id);

        //根据id去查询订单的详情
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId",id);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);

        //组装OrderOrderItem对象
        OrderOrderItem orderOrderItem = new OrderOrderItem();
        orderOrderItem.setOrder(order);
        orderOrderItem.setOrderItemList(orderItems);


        return orderOrderItem;
    }

    /**
     * 查询订单状态
     * @param id
     * @return
     */
    public List<Order> findOrdersStatus(String id) {
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderStatus",id);
        return orderMapper.selectByExample(example);
    }

    /**
     * 批量发货
     * @param orderList
     */
    @Transactional
    public void updateOrdersStatus(List<Order> orderList) {
        for (Order order : orderList) {

            if (order.getShippingName()==null || order.getShippingCode()==null){
                throw new RuntimeException("物流或订单编号不可为空");
            }
        }

        Date date = new Date();

        for (Order order : orderList) {
            order.setOrderStatus("3");
            order.setConsignStatus("2");
            order.setConsignTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);

            //发货日志
            OrderLog orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId()+"");
            orderLog.setOperater("admin");
            orderLog.setOperateTime(date);
            if(order.getId() != null && !"".equals((order.getId()))){
                orderLog.setOrderId(order.getId());
            }
            orderLog.setOrderStatus(order.getOrderStatus());
            orderLog.setPayStatus(order.getPayStatus());
            orderLog.setConsignStatus(order.getConsignStatus());
            orderLog.setRemarks("订单发货");
            orderLogMapper.insert(orderLog);
        }

    }

    /**
     * 关闭超时订单
     */
    public void orderTimeOutLogic() {
        //获取设定的超时时间
        OrderConfig orderConfig = orderConfigMapper.selectByPrimaryKey(1);
        Integer orderTimeout = orderConfig.getOrderTimeout();
        //那设定的时间求超时的时间节点
        LocalDateTime localDateTime = LocalDateTime.now().minusMinutes(orderTimeout);
        //筛选所有超时的订单
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        Example.Criteria criteria1 = criteria.andLessThan("createTime",localDateTime);
        List<Order> orders = orderMapper.selectByExample(example);
        //关闭所有超时订单
        for (Order order : orders) {
            //记录订单变动日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOperater("system");// 系统
            orderLog.setOperateTime(new Date());//当前日期
            orderLog.setOrderStatus("4");
            orderLog.setPayStatus(order.getPayStatus());
            orderLog.setConsignStatus(order.getConsignStatus());
            orderLog.setRemarks("超时订单，系统自动关闭");
            orderLog.setOrderId(order.getId());
            orderLogMapper.insert(orderLog);
            //关闭订单
            order.setOrderStatus("4");
            order.setCloseTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
        }
    }

    /**
     * 合并订单
     * @param one
     * @param two
     */
    @Override
    public void merge(String one, String two) {
        Order OneOrder = orderMapper.selectByPrimaryKey(one);
        Order TwoOrder = orderMapper.selectByPrimaryKey(two);
        //String oneId = OneOrder.getId();
        //String twoId = TwoOrder.getId();
        //2个订单的金额累加
        Integer sum=0;
        String id = idWorker.nextId()+"";
        //查主订单所有的订单详情
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", one);
        List<OrderItem> oneOrderItems = orderItemMapper.selectByExample(example);
        for (OrderItem oneOrderItem : oneOrderItems) {
            oneOrderItem.setOrderId(id);
            orderItemMapper.updateByPrimaryKeySelective(oneOrderItem);
            sum += oneOrderItem.getMoney();
        }
        //查合并订单的所有的订单详情
        Example example1 = new Example(OrderItem.class);
        Example.Criteria criteria1 = example.createCriteria();
        criteria.andEqualTo("orderId", two);
        List<OrderItem> twoOrderItems = orderItemMapper.selectByExample(example1);
        for (OrderItem twoOrderItem : twoOrderItems) {
            twoOrderItem.setOrderId(id);
            orderItemMapper.updateByPrimaryKeySelective(twoOrderItem);
            sum += twoOrderItem.getMoney();
        }
        //生成一个新的订单
        OneOrder.setId(id);
        OneOrder.setPayMoney(sum);
        OneOrder.setCreateTime(new Date());
        //添加新的订单
        orderMapper.insert(OneOrder);
        //删除2个旧的订单
        orderMapper.deleteByPrimaryKey(one);
        orderMapper.deleteByPrimaryKey(two);

        //
    }

    /**
     * 根据订单编号去拆分订单
     * @param id
     */
    @Override
    public void splitOrder(String id,List<SplitOrder> splitOrderList) {
        //根据订单id去查询所有的订单详情
        Example example = new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId", id);
        List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
        String newId = idWorker.nextId()+"";
        Order order = new Order();
        //比较拆分数量是否大于订单明细数量
        for (int i = 0; i <orderItems.size() ; i++) {
            OrderItem orderItem = orderItems.get(i);
            SplitOrder splitOrder = splitOrderList.get(i);
                //获取单个订单明细的数量  >拆分的数量
                if (orderItem.getNum() < splitOrder.getNum()){
                    throw new RuntimeException("拆分数量大于订单明细数量");
                }

                //如果拆分的数量等于原订单明细的数量,那么绑定这个订单明细到新的订单上
                if (orderItem.getNum()==splitOrder.getNum()){
                    //绑定当前订单明细到新订单上
                    orderItem.setOrderId(newId);
                    orderItemMapper.updateByPrimaryKeySelective(orderItem);
                }
                //修改被拆分订单的数量
                orderItem.setNum(orderItem.getNum()-splitOrder.getNum());
                orderItemMapper.updateByPrimaryKeySelective(orderItem);
                //把拆分出来的 一定数量的商品添加到订单详情表,并且绑定到新订单上
                orderItem.setNum(splitOrder.getNum());
                orderItem.setOrderId(newId);
                orderItemMapper.insert(orderItem);
        }

        //创建新拆分的订单
        order.setId(newId);
        order.setCreateTime(new Date());
        orderMapper.insert(order);

    }


    @Autowired
    private CartService cartService;

    @Reference
    private SkuService skuService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 保存订单
     * @param order
     * @return
     */
    @Override
    public Map<String, Object> addOrder(Order order) {
        //1.查询新的购物车
        List<Map<String, Object>> cartList = cartService.findNewOrderItemList(order.getUsername());
        //2.获取选中的购物车
        List<OrderItem> orderItemList = cartList.stream()
                .filter(cart -> (boolean) cart.get("checked") == true)
                .map(cart -> (OrderItem) cart.get("item"))
                .collect(Collectors.toList());
        //3.扣除库存
        boolean isOk = skuService.deductionStock(orderItemList);
        if (!isOk) {  //返回false
            throw new RuntimeException("库存不足！");
        }
        //通过最终一致性的分布式解决方案 来控制sku 库存的回滚  用rabbitMq 实现
        try {
            //4.保存订单主表
            order.setId(idWorker.nextId() + ""); //设置订单ID
            //合计数计算
            IntStream numStream = orderItemList.stream().mapToInt(OrderItem::getNum);
            IntStream moneyStream = orderItemList.stream().mapToInt(OrderItem::getMoney);
            int totalNum = numStream.sum();  // 总数量
            int totalMoney = moneyStream.sum();  // 总金额
            int preMoney = cartService.preferential(order.getUsername()); //优惠金额
            order.setTotalNum(totalNum);
            order.setTotalMoney(totalMoney);
            order.setPreMoney(preMoney); //设置优惠金额
            order.setPayMoney(totalMoney - preMoney); //设置实付金额
            order.setCreateTime(new Date());  //订单创建时间
            order.setPayStatus("0");  //支付状态  未支付
            order.setOrderStatus("0");  //订单状态  未付款
            order.setConsignStatus("0"); //发货状态 未发货
            orderMapper.insert(order);  //保存主订单
            //5.保存订单明细表
            //计算实付金额的比例 proportion
            double proportion = (double) (order.getPayMoney() / totalMoney);
            for (OrderItem orderItem : orderItemList) {
                orderItem.setId(idWorker.nextId() + ""); //设置订单详细ID
                orderItem.setOrderId(order.getId());  //设置关联的订单ID
                orderItem.setPayMoney((int) (orderItem.getMoney() * proportion)); //单件商品实际支付金额
                orderItemMapper.insert(orderItem);
            }
            //发送消息队列  创建订单号状态消息队列 用于后续支付状态的查询
            rabbitTemplate.convertAndSend("", "queue.ordercreate", order.getId());
            // int x =3/0; // 制造错误！
        }catch (Exception e) {
            e.printStackTrace();
            //发送消息队列
            rabbitTemplate.convertAndSend("","queue.skuBack", JSON.toJSONString(orderItemList));
            throw new RuntimeException("创建订单失败！"); //设置了事务还是要抛出异常
        }

        //6.提交订单后要做的是：
        //清空选中提交订单的购物车
        cartService.deleteCheckedCart(order.getUsername());
        //保存订单号和实付金额 传递到前端
        Map<String,Object> map = new HashMap<>();
        map.put("ordersn",order.getId());  //订单号
        map.put("money",order.getPayMoney()); //实付金额
        return map;

    }

    /**
     * 支付成功修改订单状态
     * @param orderId
     * @param transactionId  交易流水号
     */
    @Override
    public void updatePayStatus(String orderId, String transactionId) {
        Order order = findById(orderId);
        //查询订单是否存在 并且订单为未支付状态
        if (order != null && "0".equals(order.getPayStatus())){
            //修改订单状态
            order.setPayStatus("1");
            order.setOrderStatus("1"); //订单状态
            order.setUpdateTime(new Date()); //修改日期
            order.setPayTime(new Date()) ; //支付日期
            order.setTransactionId(transactionId); //交易流水号
            orderMapper.updateByPrimaryKeySelective(order); //修改
            //记录订单日志
            OrderLog orderLog = new OrderLog();
            orderLog.setId(idWorker.nextId()+"");
            orderLog.setOrderId(order.getId());
            orderLog.setOperater("system");  //设置操作者为系统默认
            orderLog.setOperateTime(new Date());  //操作时间
            orderLog.setOrderStatus("1");
            orderLog.setPayStatus("1");
            orderLog.setRemarks("交易流水号"+transactionId);
            orderLogMapper.insert(orderLog); //增加日志
        }



    }

    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 订单id
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andLike("id","%"+searchMap.get("id")+"%");
            }
            // 支付类型，1、在线支付、0 货到付款
            if(searchMap.get("payType")!=null && !"".equals(searchMap.get("payType"))){
                criteria.andLike("payType","%"+searchMap.get("payType")+"%");
            }
            // 物流名称
            if(searchMap.get("shippingName")!=null && !"".equals(searchMap.get("shippingName"))){
                criteria.andLike("shippingName","%"+searchMap.get("shippingName")+"%");
            }
            // 物流单号
            if(searchMap.get("shippingCode")!=null && !"".equals(searchMap.get("shippingCode"))){
                criteria.andLike("shippingCode","%"+searchMap.get("shippingCode")+"%");
            }
            // 用户名称
            if(searchMap.get("username")!=null && !"".equals(searchMap.get("username"))){
                criteria.andLike("username","%"+searchMap.get("username")+"%");
            }
            // 买家留言
            if(searchMap.get("buyerMessage")!=null && !"".equals(searchMap.get("buyerMessage"))){
                criteria.andLike("buyerMessage","%"+searchMap.get("buyerMessage")+"%");
            }
            // 是否评价
            if(searchMap.get("buyerRate")!=null && !"".equals(searchMap.get("buyerRate"))){
                criteria.andLike("buyerRate","%"+searchMap.get("buyerRate")+"%");
            }
            // 收货人
            if(searchMap.get("receiverContact")!=null && !"".equals(searchMap.get("receiverContact"))){
                criteria.andLike("receiverContact","%"+searchMap.get("receiverContact")+"%");
            }
            // 收货人手机
            if(searchMap.get("receiverMobile")!=null && !"".equals(searchMap.get("receiverMobile"))){
                criteria.andLike("receiverMobile","%"+searchMap.get("receiverMobile")+"%");
            }
            // 收货人地址
            if(searchMap.get("receiverAddress")!=null && !"".equals(searchMap.get("receiverAddress"))){
                criteria.andLike("receiverAddress","%"+searchMap.get("receiverAddress")+"%");
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if(searchMap.get("sourceType")!=null && !"".equals(searchMap.get("sourceType"))){
                criteria.andLike("sourceType","%"+searchMap.get("sourceType")+"%");
            }
            // 交易流水号
            if(searchMap.get("transactionId")!=null && !"".equals(searchMap.get("transactionId"))){
                criteria.andLike("transactionId","%"+searchMap.get("transactionId")+"%");
            }
            // 订单状态
            if(searchMap.get("orderStatus")!=null && !"".equals(searchMap.get("orderStatus"))){
                criteria.andLike("orderStatus","%"+searchMap.get("orderStatus")+"%");
            }
            // 支付状态
            if(searchMap.get("payStatus")!=null && !"".equals(searchMap.get("payStatus"))){
                criteria.andLike("payStatus","%"+searchMap.get("payStatus")+"%");
            }
            // 发货状态
            if(searchMap.get("consignStatus")!=null && !"".equals(searchMap.get("consignStatus"))){
                criteria.andLike("consignStatus","%"+searchMap.get("consignStatus")+"%");
            }
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andLike("isDelete","%"+searchMap.get("isDelete")+"%");
            }

            // 数量合计
            if(searchMap.get("totalNum")!=null ){
                criteria.andEqualTo("totalNum",searchMap.get("totalNum"));
            }
            // 金额合计
            if(searchMap.get("totalMoney")!=null ){
                criteria.andEqualTo("totalMoney",searchMap.get("totalMoney"));
            }
            // 优惠金额
            if(searchMap.get("preMoney")!=null ){
                criteria.andEqualTo("preMoney",searchMap.get("preMoney"));
            }
            // 邮费
            if(searchMap.get("postFee")!=null ){
                criteria.andEqualTo("postFee",searchMap.get("postFee"));
            }
            // 实付金额
            if(searchMap.get("payMoney")!=null ){
                criteria.andEqualTo("payMoney",searchMap.get("payMoney"));
            }

        }
        return example;
    }

}
